home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / gnulib / libsrc98.zoo / scandir.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-04-25  |  1.8 KB  |  82 lines

  1. /*
  2. **  SCANDIR
  3. **  Scan a directory, collecting all (selected) items into a an array.
  4. */
  5.  
  6. #include <stdlib.h>    /* for qsort */
  7. #include <sys/types.h>
  8. #include <sys/dir.h>
  9. #include <string.h>
  10.  
  11. #ifndef _COMPILER_H
  12. #include <compiler.h>
  13. #endif
  14.  
  15. #ifndef NULL
  16. #define NULL 0
  17. #endif
  18.  
  19. /* Initial guess at directory size. */
  20. #define INITIAL_SIZE    20
  21.  
  22.  
  23. int
  24. scandir(name, list, selector, sorter)
  25.     char          *name;
  26.     struct direct    ***list;
  27.     int             (*selector) __PROTO((struct direct *entp));
  28.     int             (*sorter) __PROTO((const void *, const void *));
  29. {
  30.     register struct direct     **names;
  31.     register struct direct      *entp;
  32.     register DIR      *dirp;
  33.     register int       i;
  34.     register int       size;
  35.  
  36.     /* Get initial list space and open directory. */
  37.     size = INITIAL_SIZE;
  38.     names = (struct direct **)malloc(size * sizeof names[0]);
  39.     if (names == NULL)
  40.     return -1;
  41.     dirp = opendir(name);
  42.     if (dirp == NULL)
  43.     return -1;
  44.  
  45.     /* Read entries in the directory. */
  46.     for (i = 0; entp = readdir(dirp); )
  47.     if (selector == NULL || (*selector)(entp)) {
  48.         /* User wants them all, or he wants this one. */
  49.         if (++i >= size) {
  50.         size <<= 1;
  51.         names = (struct direct **)
  52.             realloc((char *)names, size * sizeof names[0]);
  53.         if (names == NULL) {
  54.             closedir(dirp);
  55.             return -1;
  56.         }
  57.         }
  58.  
  59.         /* Copy the entry. */
  60.         names[i - 1] = (struct direct *)malloc(DIRSIZ(entp));
  61.         if (names[i - 1] == NULL) {
  62.         closedir(dirp);
  63.         return -1;
  64.         }
  65.         names[i - 1]->d_ino = entp->d_ino;
  66.         names[i - 1]->d_reclen = entp->d_reclen;
  67.         names[i - 1]->d_namlen = entp->d_namlen;
  68.         (void)strcpy(names[i - 1]->d_name, entp->d_name);
  69.     }
  70.  
  71.     /* Close things off. */
  72.     names[i] = NULL;
  73.     *list = names;
  74.     closedir(dirp);
  75.  
  76.     /* Sort? */
  77.     if (i && sorter)
  78.     qsort((char *)names, i, sizeof names[0], sorter);
  79.  
  80.     return i;
  81. }
  82.